package com.ruoyi.system.controller;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysQuestion;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.diagnosis.ScoreUtil;
import com.ruoyi.system.domain.SysDiagnosisTask;
import com.ruoyi.system.domain.SysNaire;
import com.ruoyi.system.service.ISysDiagnosisTaskService;
import com.ruoyi.system.service.ISysNaireService;
import com.ruoyi.system.service.ISysQuestionService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysDiagnosisDetail;
import com.ruoyi.system.service.ISysDiagnosisDetailService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 诊断详细记录Controller
 *
 * @author baimei
 * @date 2022-06-12
 */
@RestController
@RequestMapping("/system/diagnosisdetail")
public class SysDiagnosisDetailController extends BaseController {
    @Autowired
    private ISysDiagnosisDetailService sysDiagnosisDetailService;

    @Autowired
    private ISysNaireService sysNaireService;

    @Autowired
    private ISysQuestionService sysQuestionService;

    @Autowired
    private ISysDiagnosisTaskService sysDiagnosisTaskService;

    /**
     * 查询诊断详细记录列表
     */
//    @PreAuthorize("@ss.hasPermi('system:diagnosisdetail:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysDiagnosisDetail sysDiagnosisDetail) {
        startPage();
        List<SysDiagnosisDetail> list = sysDiagnosisDetailService.selectSysDiagnosisDetailList(sysDiagnosisDetail);
        return getDataTable(list);
    }

    /**
     * 导出诊断详细记录列表
     */
//    @PreAuthorize("@ss.hasPermi('system:diagnosisdetail:export')")
    @Log(title = "诊断详细记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysDiagnosisDetail sysDiagnosisDetail) {
        List<SysDiagnosisDetail> list = sysDiagnosisDetailService.selectSysDiagnosisDetailList(sysDiagnosisDetail);
        ExcelUtil<SysDiagnosisDetail> util = new ExcelUtil<SysDiagnosisDetail>(SysDiagnosisDetail.class);
        util.exportExcel(response, list, "诊断详细记录数据");
    }

    /**
     * 获取诊断详细记录详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:diagnosisdetail:query')")
    @GetMapping(value = "/{companyId}")
    public AjaxResult getInfo(@PathVariable("companyId") Long companyId) {
        return AjaxResult.success(sysDiagnosisDetailService.selectSysDiagnosisDetailByCompanyId(companyId));
    }

    /**
     * 新增诊断详细记录
     */
//    @PreAuthorize("@ss.hasPermi('system:diagnosisdetail:add')")
    @Log(title = "诊断详细记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysDiagnosisDetail sysDiagnosisDetail) {
        return toAjax(sysDiagnosisDetailService.insertSysDiagnosisDetail(sysDiagnosisDetail));
    }
    /**
     * 批量新增诊断详细记录
     */
    @Log(title = "诊断详细记录", businessType = BusinessType.INSERT)
    @PostMapping("/batch")
    public AjaxResult batchAdd(@RequestBody Map<String, Object> params) {
        Long companyId = Long.parseLong(params.get("companyId") + "");
        Long naireId = Long.parseLong(params.get("naireId") + "");
        String scores = params.get("scores") + "";
        JSONObject json = JSON.parseObject(scores);
        int rows = 1;
        for (String key : json.keySet()) {
            double score = json.getDouble(key);
            Long questionId = Long.parseLong(key);
            SysDiagnosisDetail sysDiagnosisDetail = new SysDiagnosisDetail();
            sysDiagnosisDetail.setCompanyId(companyId);
            sysDiagnosisDetail.setNaireId(naireId);
            sysDiagnosisDetail.setQuestionId(questionId);
            sysDiagnosisDetail.setScore(score);
            SysDiagnosisDetail tsysDiagnosisDetail1 = sysDiagnosisDetailService.selectSysDiagnosisDetailByIds(sysDiagnosisDetail);

            if (StringUtils.isNotNull(tsysDiagnosisDetail1)) {
                if (tsysDiagnosisDetail1.getScore().doubleValue() != sysDiagnosisDetail.getScore().doubleValue()) {
                    sysDiagnosisDetail.setUpdateTime(DateUtils.getNowDate());
                    sysDiagnosisDetail.setUpdateBy(getUsername());
                    rows = sysDiagnosisDetailService.updateSysDiagnosisDetail(sysDiagnosisDetail);
                }

            } else {
                sysDiagnosisDetail.setCreateTime(DateUtils.getNowDate());
                sysDiagnosisDetail.setDiagnosisBy(getUsername());
                rows = sysDiagnosisDetailService.insertSysDiagnosisDetail(sysDiagnosisDetail);
            }
        }


        return toAjax(rows);
    }
    /**
     * 自动评分
     */
    @Log(title = "诊断详细记录", businessType = BusinessType.INSERT)
    @PostMapping("/autoscoring")
    public AjaxResult autoScoring(@RequestBody SysDiagnosisDetail dquery) {
        Long companyId = dquery.getCompanyId();
        Long naireId = dquery.getNaireId();

        SysDiagnosisTask qtask=new SysDiagnosisTask();
        qtask.setCompanyId(companyId);
        qtask.setNaireId(naireId);

        List<SysDiagnosisTask>tasks=sysDiagnosisTaskService.selectSysDiagnosisTaskList(qtask);
        if(tasks==null||tasks.size()==0)
            return AjaxResult.error("Cannot find the corresponding task");
        SysDiagnosisTask task= tasks.get(0);
        task.setStatus("4");
        sysDiagnosisTaskService.updateSysDiagnosisTask(task);

        SysNaire naire = sysNaireService.selectSysNaireByNaireId(dquery.getNaireId());
        List<String> quesetionIds = Arrays.asList(naire.getQuestions().substring(1, naire.getQuestions().length() - 1).split(","));


        List<SysDiagnosisDetail> dds = sysDiagnosisDetailService.selectSysDiagnosisDetailList(dquery);

        HashMap<Long, Double> scores = new HashMap<>();
        List<Long> ignores = new ArrayList<>();
        if (dds != null) {
            for (SysDiagnosisDetail d : dds) {
                if (d.getUpdateBy() != null) {
                    ignores.add(d.getQuestionId());
                } else {
                    scores.put(d.getQuestionId(), d.getScore());
                }
            }
        }

        SysQuestion qquery = new SysQuestion();
        qquery.setNaireId(dquery.getNaireId());
        qquery.setCompanyId(dquery.getCompanyId());
        List<SysQuestion> questions = sysQuestionService.selectSysQuestionListWithRecords(qquery);

        for (SysQuestion question : questions) {
            if(!quesetionIds.contains(question.getQuestionId()+""))
                continue;

            if (ignores.contains(question.getQuestionId()))
                continue;


            double score = ScoreUtil.getGrade(question);
            if (scores.containsKey(question.getQuestionId()) && score == scores.get(question.getQuestionId()))
                continue;

            SysDiagnosisDetail sysDiagnosisDetail = new SysDiagnosisDetail();
            sysDiagnosisDetail.setCompanyId(companyId);
            sysDiagnosisDetail.setNaireId(naireId);
            sysDiagnosisDetail.setQuestionId(question.getQuestionId());
            sysDiagnosisDetail.setScore(score);


            sysDiagnosisDetailService.deleteSysDiagnosisDetailByIds(sysDiagnosisDetail);


            sysDiagnosisDetail.setCreateTime(DateUtils.getNowDate());
            sysDiagnosisDetail.setDiagnosisBy(getUsername());
            sysDiagnosisDetailService.insertSysDiagnosisDetail(sysDiagnosisDetail);

        }


        return AjaxResult.success("自动评分成功");
    }


    /**
     * 修改诊断详细记录score = 5.0
     */
//    @PreAuthorize("@ss.hasPermi('system:diagnosisdetail:edit')")
    @Log(title = "诊断详细记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysDiagnosisDetail sysDiagnosisDetail) {
        return toAjax(sysDiagnosisDetailService.updateSysDiagnosisDetail(sysDiagnosisDetail));
    }

    /**
     * 删除诊断详细记录
     */
//    @PreAuthorize("@ss.hasPermi('system:diagnosisdetail:remove')")
    @Log(title = "诊断详细记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{companyIds}")
    public AjaxResult remove(@PathVariable Long[] companyIds) {
        return toAjax(sysDiagnosisDetailService.deleteSysDiagnosisDetailByCompanyIds(companyIds));
    }
}
